package com.easy.framework.security.config;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Configuration
public class JwtConfig {

    private static final String PRIVATE_KEY_STR = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8REpQA+DtFM0I\n" +
            "K9TYKo8eeFCgolDx0UD14lVAHGPILmqyOITO83J9l/Qcv1H/4X4IcrZtsE1DYyq0\n" +
            "OtxDVP1hBDZAllbd6oCDoRyxGdHfXK91PWbUB+1rK07AMblXeY4yxZDEjcBWF79n\n" +
            "G5phRRGdZ5fToVkYAvK15aidAwEzCLJRIyrxYbMZ2YDtgFs68JdmGH7sZl0P2ncu\n" +
            "MABlEWj1Seclwo2DziofhPc/1XeGrrbrgjWUOgX9QpDIVZ3r/7X1TXlL1vmFLi/h\n" +
            "MeXeHEoP676Y3JDH6Mn572zDciLj6ND3LuSyjMIzRxOBcjGkGT2jqACbrG9ZELRR\n" +
            "bOEFguOHAgMB9/8CggEAG8JA7UuoDXgh+AaGs0IrnjsHRQWCKqHQsSeaXHGIhwBK\n" +
            "pL81iE9k0yEZucIE6OPr7wb4Rn389vKXReouAMXaep+audC8d331I445upbX2e6j\n" +
            "d8UY2x4I6ZlJOxkZeMBsB6ClZVchYUoCCP7dvKB+ajsYZH7tx2nfZu7uIA/XiiQd\n" +
            "DLJqeeSHSK9AC6pkrclBLxm+s/OPYJlUPgfb0AzHzQrVOYz/01epHznRLIeTj6V7\n" +
            "7Jg5EDbzDM4nfjnm1kWiE+p+K8EAOlzIA4Pij+SxwFlwI2rE9oneFkf2lyE/sNbA\n" +
            "mQFVux1rkcQdqGWmH0x+FiIKHyJ5kazip2ub8ol7jwKBgQD+xCFrEg8cciFO4C04\n" +
            "t7JwTHZBL98+VygHqDgoTKwTxHe1DiDiyofpp5sz8RRCZn4emSruzBVVvSV+UYn9\n" +
            "YZW1Eekjxm3orML+beCxFcHnH8+IT9MmoE05BMLaFq/17JvYaTaVm+JTcgUC6TOS\n" +
            "KrxzKXgjHyskf9AJ0dBqfVGG7wKBgQC9LbYKtS24L8boTrTR+xnNgIXrLO594o4O\n" +
            "5FV+me6UjBsSpWigRWZv3b27o6Ku2FOh5PB26YvZjiFbTBAdflAZ8RedOEl5GhwM\n" +
            "JDoRDbSUGcOPphl5FXKzoJNxq7Xr/imNX2wLw054+qrGEtp2lVeOnF98zcruLg+S\n" +
            "frvYbsIs6QKBgFNuD1IZ5OumgkUIW8cg7po/kUu/FsuMIsKDUpZQMzVWOsTYDpQz\n" +
            "rl9QbtVtiYrPmdsKKhp1P+LMmtW6kgbIBoZ5rgJexVbNAEs9ewcv7MqoMTlIqroj\n" +
            "e6UBNkF6dtVxtVML02HvrcYhnM2S6wtzho+I++QxFI0EY5qmwOxFbY7XAoGAOh4I\n" +
            "dlF0GQmyAPxCqivmaKFgEGRz7wqllj+pemPEDoskRIMxTxB2DzswLzOt0udU7d6n\n" +
            "n6AHJbg1Wtx7WTXG2m1x5OluMXq/h9D6WzMx5Vm2DyffVEURVBgQ9mmRIHSB/ggj\n" +
            "Qxqvpnp2vdG4V8iOlW7jCdxHs4HR4PdeLaSDWvcCgYEAkUdO0EpbdflhmED3CJP8\n" +
            "/3RpxwnEP2gadUgQ0/FRavDF9NPy1SpeeF6qWR9GXCQ83kXUQsXVsAr6nEkXZFC3\n" +
            "RPgMCn2Gfo0KGwOZJkzrVPoSRzx/TNnfLHzEYaWQbHi72FCZkiRIumFYSv/fueFk\n" +
            "QjXSN8nNm9rDLwUh6BLxSUY=";

    private static final String PUBLIC_KEY_STR = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvERKUAPg7RTNCCvU2CqP\n" +
            "HnhQoKJQ8dFA9eJVQBxjyC5qsjiEzvNyfZf0HL9R/+F+CHK2bbBNQ2MqtDrcQ1T9\n" +
            "YQQ2QJZW3eqAg6EcsRnR31yvdT1m1AftaytOwDG5V3mOMsWQxI3AVhe/ZxuaYUUR\n" +
            "nWeX06FZGALyteWonQMBMwiyUSMq8WGzGdmA7YBbOvCXZhh+7GZdD9p3LjAAZRFo\n" +
            "9UnnJcKNg84qH4T3P9V3hq6264I1lDoF/UKQyFWd6/+19U15S9b5hS4v4THl3hxK\n" +
            "D+u+mNyQx+jJ+e9sw3Ii4+jQ9y7ksozCM0cTgXIxpBk9o6gAm6xvWRC0UWzhBYLj\n" +
            "hwIDAff/";
    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    private RSAPrivateKey getPrivateKey() {
        try {
            String pem = PRIVATE_KEY_STR.replaceAll("\\s", "");
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem));
            return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private RSAPublicKey getPublicKey() {
        try {
            String pem = PUBLIC_KEY_STR.replaceAll("\\s", "");
            X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(pem));
            return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        RSAPrivateKey privateKey = getPrivateKey();
        RSAPublicKey publicKey = getPublicKey();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID("3b485475-d387-499b-b558-dc52f6afe791")
                .build();
        return new ImmutableJWKSet<>(new JWKSet(rsaKey));
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
        return new NimbusJwtEncoder(jwkSource);
    }
}
